/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.zhihu.question.service.impl;

import me.zhengjie.modules.zhihu.question.domain.ZhihuQuestion;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.zhihu.question.repository.ZhihuQuestionRepository;
import me.zhengjie.modules.zhihu.question.service.ZhihuQuestionService;
import me.zhengjie.modules.zhihu.question.service.dto.ZhihuQuestionDto;
import me.zhengjie.modules.zhihu.question.service.dto.ZhihuQuestionQueryCriteria;
import me.zhengjie.modules.zhihu.question.service.mapstruct.ZhihuQuestionMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王超
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2022-01-05
 **/
@Service
@RequiredArgsConstructor
public class ZhihuQuestionServiceImpl implements ZhihuQuestionService {

    private final ZhihuQuestionRepository zhihuQuestionRepository;
    private final ZhihuQuestionMapper zhihuQuestionMapper;

    @Override
    public Map<String, Object> queryAll(ZhihuQuestionQueryCriteria criteria, Pageable pageable) {
        Page<ZhihuQuestion> page = zhihuQuestionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(zhihuQuestionMapper::toDto));
    }

    @Override
    public List<ZhihuQuestionDto> queryAll(ZhihuQuestionQueryCriteria criteria) {
        return zhihuQuestionMapper.toDto(zhihuQuestionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public ZhihuQuestionDto findById(String id) {
        ZhihuQuestion zhihuQuestion = zhihuQuestionRepository.findById(id).orElseGet(ZhihuQuestion::new);
        ValidationUtil.isNull(zhihuQuestion.getId(), "ZhihuQuestion", "id", id);
        return zhihuQuestionMapper.toDto(zhihuQuestion);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhihuQuestionDto create(ZhihuQuestion resources) {
        resources.setId(IdUtil.simpleUUID());
        return zhihuQuestionMapper.toDto(zhihuQuestionRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ZhihuQuestion resources) {
        ZhihuQuestion zhihuQuestion = zhihuQuestionRepository.findById(resources.getId()).orElseGet(ZhihuQuestion::new);
        ValidationUtil.isNull(zhihuQuestion.getId(), "ZhihuQuestion", "id", resources.getId());
        zhihuQuestion.copy(resources);
        zhihuQuestionRepository.save(zhihuQuestion);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            zhihuQuestionRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ZhihuQuestionDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZhihuQuestionDto zhihuQuestion : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("标题", zhihuQuestion.getTitle());
            map.put("浏览数", zhihuQuestion.getVisitCount());
            map.put("问题URL", zhihuQuestion.getUrl());
            map.put("关注人数", zhihuQuestion.getFollowerCount());
            map.put("回答总数", zhihuQuestion.getAnswerCount());
            map.put(" createTime", zhihuQuestion.getCreateTime());
            map.put(" updateTime", zhihuQuestion.getUpdateTime());
            map.put("是否删除", zhihuQuestion.getIsDeleted());
            map.put("主题关键词ID", zhihuQuestion.getThemeKeywordId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void batchCreate(HttpServletRequest request, String themeId) throws IOException {
        Map<String,String> map = new HashMap<>();
        long startTime = System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        List<ZhihuQuestion> list = new ArrayList<>();
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {

//                    String path = "C:/eladmin/upload/" + startTime + "/" + file.getOriginalFilename();
//                    File f = new File(path);
//                    //上传
//                    if (!f.exists()){
//                        f.mkdirs();
//                    }
//                    file.transferTo(f);

                    HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
                    Sheet sheet = wb.getSheetAt(0);
                    for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                        //循环获取工作表的每一行
                        Row sheetRow = sheet.getRow(i);
                        ZhihuQuestion question = new ZhihuQuestion();
                        question.setAnswerCount("1")
                        .setFollowerCount("1")
                        .setVisitCount("1")
                        .setIsDeleted("0")
                        .setThemeId("cb8260e7350c4ae097dcfe6906ce9522")
                        .setThemeKeywordId("1")
                        .setAnswerCount("1");
                        for (int j = 0; j < sheetRow.getPhysicalNumberOfCells(); j++) {
                            String s = sheetRow.getCell(j).getStringCellValue();
                            if (j == 2){
                                question.setTitle(s);
                            }else if (j == 3){
                                question.setId(s.substring(s.lastIndexOf("/")+1));
                                question.setUrl(s);
                            }
                            }
                        if (!map.containsKey(question.getId())){
                            list.add(question);
                            map.put(question.getId(),"1");
                        }

                        }
                    wb.close();
                    }

                }

            }
            long endTime = System.currentTimeMillis();
            System.out.println("方法三的运行时间：" + String.valueOf(endTime - startTime) + "ms");
            zhihuQuestionRepository.saveAll(list);
        }
    }
